const errorHandler = (err, req, res, next) => {
  console.error('Error:', err);

  if (err.status === 429 || err.statusCode === 429) {
    const retryAfter = err.retryAfter ? Math.ceil(err.retryAfter / 1000) : 60;
    res.set('Retry-After', retryAfter.toString());
    return res.status(429).json({
      error: 'Rate limit exceeded',
      message: 'API quota exceeded. Please try again later.',
      retryAfter: retryAfter,
      details: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
  }

  if (err.status === 'PERMISSION_DENIED') {
    return res.status(403).json({
      error: 'Permission denied',
      message: 'API key is invalid or missing permissions'
    });
  }

  if (err.name === 'MulterError') {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({
        error: 'File too large',
        message: `File size exceeds the maximum limit`
      });
    }
    return res.status(400).json({
      error: 'File upload error',
      message: err.message
    });
  }

  if (err.name === 'ValidationError') {
    return res.status(400).json({
      error: 'Validation error',
      message: err.message
    });
  }

  const statusCode = err.statusCode || 500;
  const message = err.message || 'Internal server error';

  res.status(statusCode).json({
    error: statusCode === 500 ? 'Internal server error' : err.name || 'Error',
    message: message,
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
};

module.exports = errorHandler;